
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class ServletUI extends HttpServlet {
    private  String message;

    public void init() throws ServletException{
        message = "Hello world";
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)throws ServletException, IOException{
        response.setContentType("text/html;charset=gb2312");

        //Main
//        PrintWriter out = response.getWriter();
//        out.println("<h1>"+message+"</h1>");
        PrintWriter out = response.getWriter();
        String docType =
                "<!doctype html public \"-//w3c//dtd html 4.0 " +       "transitional//en\">\n";
        String chinese_support= "<head>\n" +
                "\t<meta charset=\"UTF-8\">\n" +
                "</head>";
        String back ="<input name=\"返回\" type=\"button\" id=\"btn1\" title=\"返回\" value=\"返回\" onclick=\"location.href='http://localhost:8080/hello.htm'\" />\n";
        try {
            out.println(docType + chinese_support +
                    "<html>\n" +
                    "<head><title>" + "搜索结果" + "</title></head>\n" +
//                    "<body bgcolor=\"#f0f0f0\">\n" +
//                    "<h1 align=\"center\">" + title + "</h1>\n" +
                    back +
                    getSearchResults(toChinese(request.getParameter("query"))) + "\n" +
                    "</body></html>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }


    private String getSearchResults(String search) throws Exception {
        QueryParser queryParser = new QueryParser("name", new IKAnalyzer());
        Query query = queryParser.parse(search);
        return  printResult(query);
    }

    private String toChinese(String name)throws ServletException, IOException {
        return  new String(name.getBytes("ISO-8859-1"), "UTF-8");
    }

    private static String printResult(Query query) throws Exception {
        //Create index searcher
        IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File("..\\Documents\\index").toPath()));
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        //Search
        StringBuffer stringBuffer= new StringBuffer();
        TopDocs topDocs = indexSearcher.search(query, 10);
//        System.out.println("总记录数：" + topDocs.totalHits);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        //处理结果
        for (ScoreDoc doc:scoreDocs){
            //取文档id
            int docId = doc.doc;
            //根据id取文档对象
            Document document = indexSearcher.doc(docId);
            String name = document.get("name");
            String url = document.get("url");
            String content = document.get("content").substring(0,100)+"...";
            String html_link = "<p></p>\n " + "\n\n<a href=\"" + url +"\">" + name + "</a>\n";
            stringBuffer.append(html_link);
//            <a href="http://www.baidu.com">我是一个超链接</a>
            String html_content = "<ul>\n" +
                    "\t"+content+"\n"
                    +"</ul>\n";
//            <ul>
//                    在吗？
//            </ul>
            stringBuffer.append(html_content);
        }
        indexReader.close();
        System.out.print(stringBuffer.substring(0));
        return stringBuffer.substring(0);
    }
    public void destroy(){

    }

    @Test
    public void test() throws Exception {
        System.out.print(getSearchResults("哈工大深圳"));
    }
}
